/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: syyyy
 * Date: 2025-06-18
 * Time: 20:02
 */
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

// 主程序入口类，创建登录界面并启动相关逻辑
public class LibraryApp {
    public static void main(String[] args) {
        // 在事件调度线程中创建 GUI，保证线程安全
        SwingUtilities.invokeLater(() -> {
            LoginFrame loginFrame = new LoginFrame();
            loginFrame.setVisible(true);
        });
    }
}

// 登录窗口类，继承 JFrame 来构建登录界面
class LoginFrame extends JFrame {
    private JTextField usernameField;
    private JPasswordField passwordField;

    public LoginFrame() {
        super("图书馆系统 - 登录");
        setSize(400, 300);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLocationRelativeTo(null); // 让窗口居中显示
        setLayout(new GridLayout(3, 2, 10, 10)); // 3行2列的网格布局，设置组件间距

        // 添加用户名标签和文本框
        JLabel usernameLabel = new JLabel("用户名:");
        usernameField = new JTextField();
        add(usernameLabel);
        add(usernameField);

        // 添加密码标签和密码框
        JLabel passwordLabel = new JLabel("密码:");
        passwordField = new JPasswordField();
        add(passwordLabel);
        add(passwordField);

        // 创建登录按钮并添加事件监听器
        JButton loginButton = new JButton("登录");
        loginButton.addActionListener(new LoginListener(this));
        // 单独一行放置按钮，这里通过 JPanel 来辅助布局
        JPanel buttonPanel = new JPanel();
        buttonPanel.add(loginButton);
        add(buttonPanel);
    }

    // 获取输入的用户名
    public String getUsername() {
        return usernameField.getText();
    }

    // 获取输入的密码（转为字符串）
    public String getPassword() {
        return new String(passwordField.getPassword());
    }

    // 登录验证通过后，关闭当前登录窗口并打开主界面窗口
    public void openMainFrame() {
        this.dispose();
        MainFrame mainFrame = new MainFrame();
        mainFrame.setVisible(true);
    }
}

// 登录按钮的事件监听器类，实现 ActionListener 接口处理登录逻辑
class LoginListener implements ActionListener {
    private LoginFrame loginFrame;
    // 预设的测试用户名和密码
    private static final String TEST_USERNAME = "admin";
    private static final String TEST_PASSWORD = "123456";

    public LoginListener(LoginFrame loginFrame) {
        this.loginFrame = loginFrame;
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        String username = loginFrame.getUsername();
        String password = loginFrame.getPassword();

        try {
            // 简单的非空验证
            if (username.isEmpty() || password.isEmpty()) {
                throw new IllegalArgumentException("用户名和密码不能为空");
            }
            // 验证用户名和密码是否正确
            if (TEST_USERNAME.equals(username) && TEST_PASSWORD.equals(password)) {
                JOptionPane.showMessageDialog(loginFrame, "登录成功！", "提示", JOptionPane.INFORMATION_MESSAGE);
                loginFrame.openMainFrame();
            } else {
                JOptionPane.showMessageDialog(loginFrame, "用户名或密码错误，请重新输入", "错误", JOptionPane.ERROR_MESSAGE);
            }
        } catch (IllegalArgumentException ex) {
            JOptionPane.showMessageDialog(loginFrame, ex.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
        }
    }
}

// 主界面窗口类，登录成功后显示，包含借阅书本功能
class MainFrame extends JFrame {
    public MainFrame() {
        super("图书馆系统 - 主界面");
        setSize(500, 400);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLocationRelativeTo(null);
        setLayout(new BorderLayout());

        // 创建文本区域用于显示书本信息等
        JTextArea infoArea = new JTextArea();
        infoArea.setEditable(false);
        infoArea.setText("欢迎使用图书馆系统！\n可借阅的书本：\n1. 《Java 核心技术》\n2. 《数据结构与算法分析》\n3. 《设计模式之禅》");
        JScrollPane scrollPane = new JScrollPane(infoArea);
        add(scrollPane, BorderLayout.CENTER);

        // 创建面板放置借阅相关组件
        JPanel borrowPanel = new JPanel();
        JLabel bookLabel = new JLabel("选择要借阅的书本（输入序号）:");
        JTextField bookField = new JTextField(10);
        JButton borrowButton = new JButton("借阅");

        borrowButton.addActionListener(new BorrowListener(bookField, infoArea));

        borrowPanel.add(bookLabel);
        borrowPanel.add(bookField);
        borrowPanel.add(borrowButton);
        add(borrowPanel, BorderLayout.SOUTH);
    }
}

// 借阅按钮的事件监听器类，处理借阅逻辑和异常
class BorrowListener implements ActionListener {
    private JTextField bookField;
    private JTextArea infoArea;

    public BorrowListener(JTextField bookField, JTextArea infoArea) {
        this.bookField = bookField;
        this.infoArea = infoArea;
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        String input = bookField.getText();
        try {
            if (input.isEmpty()) {
                throw new IllegalArgumentException("请输入要借阅的书本序号");
            }
            int bookIndex = Integer.parseInt(input);
            if (bookIndex < 1 || bookIndex > 3) {
                throw new IllegalArgumentException("请输入 1 - 3 之间的有效书本序号");
            }
            String bookName = "";
            switch (bookIndex) {
                case 1:
                    bookName = "《Java 核心技术》";
                    break;
                case 2:
                    bookName = "《数据结构与算法分析》";
                    break;
                case 3:
                    bookName = "《设计模式之禅》";
                    break;
            }
            infoArea.append("\n已成功借阅：" + bookName);
            JOptionPane.showMessageDialog(null, "成功借阅 " + bookName, "借阅成功", JOptionPane.INFORMATION_MESSAGE);
            bookField.setText("");
        } catch (NumberFormatException ex) {
            JOptionPane.showMessageDialog(null, "请输入有效的数字序号", "错误", JOptionPane.ERROR_MESSAGE);
            bookField.setText("");
        } catch (IllegalArgumentException ex) {
            JOptionPane.showMessageDialog(null, ex.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
            bookField.setText("");
        }
    }
}